﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Common.Authorization
{
    /// <summary>
    /// 自定义授权验证Handel
    /// </summary>
    public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionAuthorizationRequirement>
    {

        IGetFunctionCode _getFunctionCode;
        WebAppOptions _webAppOptions;
        public PermissionAuthorizationHandler(IGetFunctionCode getFunctionCode, IOptionsMonitor<WebAppOptions> webAppOptions)
        {
            _getFunctionCode = getFunctionCode;
            _webAppOptions = webAppOptions.CurrentValue;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement)
        {
            if (context.User != null)
            {
                //从当前票据获取用户信息
               
                //确认是否是管理员
                if (context.User.Identity.Name.Equals(_webAppOptions.AdminLoginName))
                {
                    context.Succeed(requirement);
                }
                else
                {
                    if (!_webAppOptions.Authorization)
                        context.Succeed(requirement);
                    //验证权限
                    var userFunctionList = await _getFunctionCode.GetCurrUserFunctionCodeAsync(context.User);
                    if (userFunctionList != null && userFunctionList.Any())
                    {
                        if (userFunctionList.Contains(requirement.FunctionCode))
                            context.Succeed(requirement);
                    }
                }
            }
        }
    }
}
